package com.example.lenovo.liweixin1601v20180702.m.http;

import android.os.Handler;
import android.os.Message;

import com.example.lenovo.liweixin1601v20180702.m.model.GetNewListener;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lenovo on 2018/7/2.
 */

public class HttpUtils {
    public static HttpUtils httpUtils;
    private final int SUCCESS = 0;
    private final int ERROR = 1;
    private MyHandler myHandler = new MyHandler();
    private GetNewListener getNewListener;

    public static HttpUtils getHttpUtils() {
        if (httpUtils == null) {
            httpUtils = new HttpUtils();
        }
        return httpUtils;
    }

    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCESS:
                    String json = (String) msg.obj;
                    getNewListener.getSuccess(json);
                    break;
                case ERROR:
                    String error = (String) msg.obj;
                    getNewListener.getError(error);
                    break;
            }
        }
    }

    //get请求
    public void OkGet(String url) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = myHandler.obtainMessage();
                message.what = ERROR;
                message.obj = e.getMessage();
                myHandler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message message = myHandler.obtainMessage();
                message.what = SUCCESS;
                message.obj = response.body().string();
                myHandler.sendMessage(message);
            }
        });
    }

    public void  setGetNewListener(GetNewListener getNewListener) {
        this.getNewListener = getNewListener;
    }

}
